<?php
/**
 * Copyright (c) 2008 Derdubor A/S
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

/** @see Keepitclose_Storage_Interface */
require_once 'Keepitclose/Storage/Interface.php';

class Keepitclose_Storage_Memcache implements Keepitclose_Storage_Interface
{
    protected $memcacheServers = array();

    public function __construct($params)
    {
        $index = 0;
    
        foreach($params as $server)
        {
            if (empty($server['host']))
            {
                throw new Keepitclose_Storage_MemcacheException("'host' field missing from server configuration with index: " . $index);
            }
        
            $memcache = new Memcache;

            $method = 'connect';
            
            if (!empty($server['persistent']))
            {
                $method = 'pconnect';
            }
            
            $result = false;

            // as $port must be 0 if using unix sockets, we use isset and not empty.
            if (isset($server['port']))
            {
                if (isset($server['timeout']))
                {
                    $result = @$memcache->$method($server['host'], $server['port'], $server['timeout']);
                }
                else
                {
                    $result = @$memcache->$method($server['host'], $server['port']);
                }
            }
            else
            {
                $result = @$memcache->$method($server['host']);
            }

            if ($result)
            {
                $this->addMemcacheServer($memcache);
            }
            
            $index++;
        }
    }

    public function get($key)
    {
        $memcache = $this->getMemcacheServerByKey($key);
        return $memcache->get($key);
    }

    public function set($key, $data, $ttl = 0)
    {
        $memcache = $this->getMemcacheServerByKey($key);
        return $memcache->set($key, $data, null, $ttl);
    }
    
    protected function getMemcacheServerByKey($key)
    {
        $serverCount = count($this->getMemcacheServers());
        
        if ($serverCount == 0)
        {
            throw new Keepitclose_Storage_MemcacheException("No available memcache servers");
        }
        
        $serverIdx = abs(crc32($key)) % $serverCount;
        return $this->getMemcacheServer($serverIdx);
    }
    
    protected function getMemcacheServers()
    {
        return $this->memcacheServers;
    }
    
    protected function getMemcacheServer($idx)
    {
        return $this->memcacheServers[$idx];
    }
    
    protected function addMemcacheServer($memcacheServer)
    {
        $this->memcacheServers[] = $memcacheServer;
    }
    
    public static function isSupported()
    {
        if (!extension_loaded("memcache"))
        {
            throw new Exception("Missing memcache extension");
        }
    }
}

class Keepitclose_Storage_MemcacheException extends Exception {}